package com.zl.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zl.mapper.RoleMapper;
import com.zl.model.RoleDto;
import com.zl.model.entity.Permission;
import com.zl.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class RoleService extends BaseServiceImpl<RoleDto> implements IRoleService {


    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageInfo selectPage(int pageSize, int pageNumber, String name) {
        PageHelper.startPage(pageSize, pageNumber);
        List<RoleDto> roleDto = roleMapper.selectByName(name);
        PageInfo<RoleDto> selectPage = new PageInfo<RoleDto>(roleDto);
        return selectPage;
    }

    @Override
    public void deletes(int[] ids) {
        roleMapper.deletes(ids);
    }

    /**
     * 根据角色id获取功能列表
     * @param id 角色id
     * @return
     */
    @Override
    public Map<String,Object> menuList(int id) {
        Map<String,Object> map= new HashMap<>();
        List<Permission> list = roleMapper.menuList(id);
        String arr[] = new String[list.size()];
        List<Permission> menulist = list.stream()
                .filter(a -> a.getParent() == 0)
//                .sorted(Comparator.comparing(Permission::getOrderNum).reversed())
                .collect(Collectors.toList());
        findChildren(list, menulist);
       for(int i=0;i<list.size();i++){
           if(list.get(i).getHave()==1){
               arr[i]=list.get(i).getId()+"";
           }
       }
        map.put("menulist",menulist);
        map.put("arr",arr);
        return map;
    }

    /**
     * 递归查询菜单
     *
     * @param list
     * @param menulist
     */
    public static void findChildren(List<Permission> list, List<Permission> menulist) {
        menulist.stream().forEach(a -> {
                    List<Permission> childrenList = new ArrayList<>();//childrenList用来存放子级
                    list.stream().forEach(b -> {
                        if (b.getParent() == a.getId()) {
                            childrenList.add(b);//将子级存入list中
                        }
                        findChildren(list, childrenList);//递归方法
                        childrenList.sort(Comparator.comparing(Permission::getOrderNum).reversed());//排序
                    });
                    a.setChildren(childrenList);
                }

        );

    }


}
